package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.constant.AccountType;
import com.qiche.dto.MerchantDto;
import com.qiche.dto.UserDto;
import com.qiche.enums.ResultEnum;
import com.qiche.model.*;
import com.qiche.service.*;
import com.qiche.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**用户管理控制器
 * Created by Linzw on 2018/01/24.
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;

    @Resource
    private MerchantService merchantService;

    @Resource
    private RoleService roleService;

    @Autowired
    private AgentService agentService;

    @PostMapping(value = "/login")
    public Result<User> login(String username, String password,boolean rememberMe, HttpSession session){
        System.out.println("------------------------------------------------");
        System.out.println("jinlai le");
        return userService.login(username,password,rememberMe);
    }

    @GetMapping(value = "/logout")
    public Result<String> logout(){
        return  userService.logout();
    }

    @RequestMapping
    public Map<String, Object> getAll(User user,
                                      @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> map = new HashMap<>();
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser.getMerchantId() != 0 && currentUser.getMerchantId() != null) {
            user.setMerchantId(currentUser.getMerchantId());
        }
        PageInfo<User> pageInfo = userService.selectByPage(user, page, limit);

        List<UserDto> dtos = new ArrayList<UserDto>();

        pageInfo.getList().forEach(userTemp -> {
            Role role = roleService.queryRoleByUserId(userTemp.getId());
            UserDto dto = new UserDto();
            BeanUtils.copyProperties(userTemp, dto);
            if (role != null) {
                dto.setRoleName(role.getRoleName());
            }
            if (userTemp.getMerchantId() != null) {
                Merchant merchant = merchantService.selectById(userTemp.getMerchantId().longValue());
                if (merchant != null) {
                    dto.setMerchantName(merchant.getName());
                }

            }
            dtos.add(dto);
        });

        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", dtos);

        return map;
    }

    /**
     * 保存用户角色
     *
     * @param userRole 用户角色 此处获取的参数的角色id是以 “,” 分隔的字符串
     * @return
     */
    @RequestMapping("/saveUserRoles")
    public Map<String, Object> saveUserRoles(@RequestBody UserRole userRole) {
        Map<String, Object> map = new HashMap<>();
        userRoleService.addUserRole(userRole);
        map.put("code", 200);
        map.put("msg", "保存成功");
        return map;

    }

    @RequestMapping(value = "/getById")
    public Result getById(@RequestParam("id") Long userId) {
        User bean = userService.selectById(userId);
        Role role = roleService.queryRoleByUserId(bean.getId());
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(bean, userDto);
        if (role != null) {
            userDto.setRoleName(role.getRoleName());
            userDto.setRoleId(role.getId());
        }
        return Result.createBySuccess(userDto);
    }

    @PostMapping("/add")
    public Result<User> add(@RequestBody User user) {
        return userService.register(user);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        int isOk = userService.updateNotNull(user);
        Role role = roleService.queryRoleByUserId(user.getId());
        if (user.getRoleId() != null && role.getId() != user.getRoleId()) {
            userRoleService.deleteRoleByUser(user.getId());
            UserRole userRole = new UserRole();
            userRole.setRoleid(user.getRoleId() + "");
            userRole.setUserid(user.getId());
            userRoleService.addUserRole(userRole);
        }
        if (isOk > 0) {
            return Result.createBySuccessMessage("更新成功");
        }
        return Result.createByErrorMessage("更新失败");


    }

    @PostMapping
    public String delete(Integer id) {
        try {
            userService.delUser(id);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }


    @RequestMapping(value = "/changeStatus")
    public Result changeStatus(Long id, Integer status) {
        User user = userService.selectById(id);

        int isUpdate = 0;
        if (user == null) {
            return Result.createByResultEnum(ResultEnum.FAILURE);
        } else {
            user.setEnable(status);
            isUpdate = userService.updateNotNull(user);
            if (isUpdate > 0) {
                return Result.createByResultEnum(ResultEnum.SUCCESS);
            } else {
                return Result.createByResultEnum(ResultEnum.FAILURE);
            }
        }
    }

    @RequestMapping(value = "/getCurrentUserInfo")
    public Result getCurrentUserInfo() {
        User user = UserUtils.getCurrentUser();
        Merchant merchant = null;
        MerchantDto merchantDto = new MerchantDto();
        if (AccountType.ADMIN != user.getAccountType() && AccountType.AGENT != user.getAccountType()) {
            merchant = merchantService.selectById(user.getMerchantId().longValue());
            BeanUtils.copyProperties(merchant, merchantDto);

        } else {
            if(AccountType.AGENT == user.getAccountType()){
                Agent agent=agentService.selectByAccountId(user.getId());

                merchantDto.setName("代理机构["+agent.getName()+"]");
                merchantDto.setMerchantImg("");
            }else  if(AccountType.ADMIN == user.getAccountType()){
                merchantDto.setName("超级管理员");
                merchantDto.setMerchantImg("");
            }


        }
        merchantDto.setUsername(user.getUsername());
        return Result.createByResultEnum(ResultEnum.SUCCESS, merchantDto);
    }


}
